<?php

namespace App\Listeners;


use App\Events\Event;
use App\Events\CourseEvent;
use App\Events\ScheduleEvent;
use App\Model\Business\Schedule;
use App\Model\Eeoapi\Eeocourse;
use App\Model\Eeoapi\Eeoschedule;


class CourseListener extends  Listener
{
    /**
     * @param CourseEvent $event
     */
    public function handle(CourseEvent $event)
    {
        switch($event->action)
        {
            case Event::CREATE:
                $this->create($event); break;
            case Event::UPDATE:
                $this->update($event); break;
            case Event::DELETE:
                $this->delete($event); break;
            case Event::STUDENT:
                if(env('ASYN_MODE')){
                    $this->syncdata($event);
                }else{
                    $this->student($event);
                }
                break;
            default: break;
        }
    }


    /**
     * 创建课程
     * @param CourseEvent $event
     * @throws \Exception
     */
    protected function create(CourseEvent $event)
    {
        try{
            $this->setUri('addCourse');
            $cfile = $this->uploadCheck($event->Filedata);
            $data = $this->dataMaker();
            $data["courseName"] = $event->courseName;
            $data["folderId"] = $event->folderId;
            $data["Filedata"] = $cfile;
            $data["expiryTime"] = $event->expiryTime;
            $this->setRequest($data);
            $result = $this->callEeoApi();

        if($result['error_info']['errno'] === 1) {
            $event->setEeoCourseId($result['data']);
            $this->getWebcast($event,$result['data'],null);
        }else{
            throw new \Exception($result['error_info']['error'], $result['error_info']['errno']);
            }
        }catch (\Exception $e){
            throw $e;
        }
    }


    /**
     * 修改课程
     * @param CourseEvent $event
     * @throws \Exception
     */
    protected function update(CourseEvent $event)
    {
        try{
            $this->setUri('editCourse');
            $cfile = $this->uploadCheck($event->Filedata);
            $data = $this->dataMaker();
            $data["courseId"] = $event->courseId;
            $data["courseName"] = $event->courseName;
            $data["folderId"] = $event->folderId;
            $data["Filedata"] = $cfile;
            $data["expiryTime"] = $event->expiryTime;
            $this->setRequest($data);
            $result = $this->callEeoApi();
            if($result['error_info']['errno'] <> 1){
                throw new \Exception($result['error_info']['error'], $result['error_info']['errno']);
            }
        }catch (\Exception $e){
            throw $e;
        }

    }


    /**
     * 删除课程
     * @param CourseEvent $event
     * @throws \Exception
     */
    protected function delete(CourseEvent $event)
    {
        try{
            if($event->courseId){
                $this->setUri('delCourse');
                $data = $this->dataMaker();
                $data["courseId"] = $event->courseId;
                $this->setRequest($data);
                $result = $this->callEeoApi();
		if ($result['error_info']['errno'] == 1 || $result['error_info']['errno'] == 149) {
                    $event->delEeoCourseId();
                } else {
                    throw new \Exception($result['error_info']['error'], $result['error_info']['errno']);
                }
            }
        }catch (\Exception $e){
            throw $e;
        }
    }

    /**
     * 课程下添加/删除学生
     * @param $event
     */
    protected function student(CourseEvent $event)
    {
        try{
            $olds = $event->getStudents(true);
            $news = $event->getStudents();
            $data = $this->dataMaker();
            $data["courseId"] = $event->courseId;
            if(!empty($olds)){
                $this->delstudents($event,$olds);
            }

            if(!empty($news)){
                $this->addstudents($event,$news);
            }
        }catch (\Exception $e){
            throw $e;
        }
    }

    /**
     * 课程下删除学生
     * @param $event
     * @param $olds
     * @throws \Exception
     *
     */

    protected function delstudents($event,$olds)
    {
        $myOlds=[];
        $data = $this->dataMaker();
        $data["courseId"] = $event->courseId;
        $this->setUri('delCourseStudentMultiple');
        foreach ($olds as $old) {
            $myOlds[] = $old['studentAccount'];
        }
        $data['studentJson'] = json_encode($myOlds);
        $data["identity"] = $event->identity;
        $this->setRequest($data);
        $result = $this->callEeoApi();
        $code = $result['error_info']['errno'];
        if (in_array($code, [1])) {
            foreach ($result['data'] as $key => $res) {
                if (!in_array($res['errno'], [1])) {
                    $msg = '学生：'.$myOlds[$key].$res['error'];
                    $data = $this->dataMaker();
                    $data["courseId"] = $event->courseId;
                    $myNews = [];
                    $org = Event::getOrg();
                    $this->setUri('addCourseStudentMultiple');
                    foreach ($olds as $new) {
                        $myNew = [];
                        $myNew['account'] = $new['studentAccount'];
                        $myNew['name'] = $new['studentName'];
                        $myNew['password'] = $org['registerDefaultPwd'];
                        $myNews[] = $myNew;
                    }
                    $data['studentJson'] = json_encode($myNews);
                    $data["isRegister"] = 1;
                    $data["identity"] = $event->identity;
                    $this->setRequest($data);
                    $result = $this->callEeoApi();
                    throw new \Exception($msg, $res['errno']);
                }
            }
        } else {
            throw new \Exception($result['error_info']['error'], $result['error_info']['errno']);
        }
    }

    /**
     * 课程下添加学生
     * @param $event
     * @param $olds
     * @throws \Exception
     *
     */

    protected function addstudents($event,$news)
    {
        $data = $this->dataMaker();
        $data["courseId"] = $event->courseId;
        $myNews = [];
        $org = Event::getOrg();
        $this->setUri('addCourseStudentMultiple');
        foreach ($news as $new) {
            $myNew = [];
            $myNew['account'] = $new['studentAccount'];
            $myNew['name'] = $new['studentName'];
            $myNew['password'] = $org['registerDefaultPwd'];
            $myNews[] = $myNew;
        }
        $data['studentJson'] = json_encode($myNews);
        $data["isRegister"] = 1;
        $data["identity"] = $event->identity;
        $this->setRequest($data);
        $result = $this->callEeoApi();
        $code = $result['error_info']['errno'];
        if (in_array($code, [1])) {
            foreach ($result['data'] as $key => $res) {
                if (!in_array($res['errno'], [1])) {
                    $msg = '学生：'.$myNews[$key]['name'].$myNews[$key]['account'].$res['error'];
                    $myOlds=[];
                    $data = $this->dataMaker();
                    $data["courseId"] = $event->courseId;
                    $this->setUri('delCourseStudentMultiple');
                    foreach ($news as $old) {
                        $myOlds[] = $old['studentAccount'];
                    }
                    $data['studentJson'] = json_encode($myOlds);
                    $data["identity"] = $event->identity;
                    $this->setRequest($data);
                    $result = $this->callEeoApi();
                    throw new \Exception($msg, $res['errno']);
                }
            }
        } else {
            throw new \Exception($result['error_info']['error'], $result['error_info']['errno']);
        }
    }

    /**
     * 异步模式添加学生
     *
     */
    protected function syncdata(CourseEvent $event)
    {
        try{
            $this->student($event);

            $schedules = [];
            $eeolist = [];
            $allschedule = Schedule::where('classeid',$event->classuid)
                ->where('type',$event->type)
                ->get();
            $eeoschedules = Eeoschedule::where('courseId',$event->courseId)
                ->get();
            foreach ($eeoschedules as $eeoschedule){
                $eeolist[] = $eeoschedule->scheduleid;
            }
            foreach ($allschedule as $schedule){
                if(!in_array($schedule->scheduleid,$eeolist)){
                    $schedules[] = $schedule;
                }
            }
            if($schedules){
                foreach ($schedules as $obj){
                    $schedulevent = new ScheduleEvent($obj, Event::CREATE);

                    # 设置 eeo course id
                    $eeocourse = Eeocourse::where('type', $event->type)
                        ->where('chimpid', $obj->classeid)
                        ->first();
                    if($eeocourse){
                        $schedulevent->setCourseID($eeocourse->eeocourseid);
                        $schedulevent->classId = 1;
                    }else{
                        throw new \Exception('获取EEO Course ID 失败');
                    }
                    event($schedulevent);
                }
            }


        }catch (\Exception $e){
            throw $e;
        }

    }
}
